<template>
  <div class="page-container">
    <div class="page-header">
      <h2 class="page-title">个人信息</h2>
    </div>

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" @click="startEdit">编辑</el-button>
            </div>
          </template>

          <el-form
            ref="profileForm"
            :model="profileData"
            :rules="rules"
            label-width="100px"
            :disabled="!isEditing"
          >
            <el-form-item label="学号" prop="usercode">
              <el-input v-model="profileData.usercode" :disabled="true" />
            </el-form-item>
            
            <el-form-item label="姓名" prop="fullName">
              <el-input v-model="profileData.fullName" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileData.email" />
            </el-form-item>

            <el-form-item label="学校">
              <el-input v-model="schoolName" :disabled="true" />
            </el-form-item>
            
            <el-form-item label="院系">
              <el-select v-model="selectedDepartment" placeholder="请选择院系" :disabled="!isEditing || !departments.length">
                <el-option
                  v-for="dept in departments"
                  :key="dept.orgId"
                  :label="dept.name"
                  :value="dept.orgId"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="专业">
              <el-select v-model="selectedMajor" placeholder="请选择专业" :disabled="!isEditing || !majors.length">
                <el-option
                  v-for="major in majors"
                  :key="major.orgId"
                  :label="major.name"
                  :value="major.orgId"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="班级">
              <el-select v-model="selectedClass" placeholder="请选择班级" :disabled="!isEditing || !classes.length">
                <el-option
                  v-for="cls in classes"
                  :key="cls.orgId"
                  :label="cls.name"
                  :value="cls.orgId"
                />
              </el-select>
            </el-form-item>

            <el-form-item v-if="isEditing">
              <el-button type="primary" @click="saveProfile">保存</el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'StudentProfilePage'
}
</script>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useUserStore } from '../../stores/user'
import request from '../../utils/request'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()

// 数据
const isEditing = ref(false)
const profileData = ref({})
const schoolName = ref('')
const departments = ref([])
const majors = ref([])
const classes = ref([])
const selectedDepartment = ref(null)
const selectedMajor = ref(null)
const selectedClass = ref(null)

// 组织层级信息
const orgHierarchy = ref({
  school: null,
  department: null,
  major: null,
  class: null
})

// 表单校验规则
const rules = {
  fullName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 方法
const loadProfile = () => {
  profileData.value = { ...userStore.userInfo }
  
  // 如果有组织ID，加载组织信息
  if (profileData.value.orgId) {
    loadOrganizationHierarchy(profileData.value.orgId)
  } else {
    // 如果没有组织ID，尝试从用户信息中获取
    getUserInfo()
  }
}

const getUserInfo = async () => {
  try {
    await userStore.getUserInfo()
    profileData.value = { ...userStore.userInfo }
    if (profileData.value.orgId) {
      loadOrganizationHierarchy(profileData.value.orgId)
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

const loadOrganizationHierarchy = async (orgId) => {
  try {
    // 获取当前组织信息
    const response = await request.get(`/organizations/${orgId}/hierarchy`)
    if (response.data) {
      const hierarchy = response.data
      
      // 设置学校信息
      if (hierarchy.school) {
        schoolName.value = hierarchy.school.name
        orgHierarchy.value.school = hierarchy.school
        
        // 加载学校下的所有院系
        const deptResponse = await request.get(`/organizations/${hierarchy.school.orgId}/children`)
        if (deptResponse.data) {
          departments.value = deptResponse.data
        }
      }
      
      // 设置院系信息
      if (hierarchy.department) {
        orgHierarchy.value.department = hierarchy.department
        selectedDepartment.value = hierarchy.department.orgId
        
        // 加载该院系下的所有专业
        const majorResponse = await request.get(`/organizations/${hierarchy.department.orgId}/children`)
        if (majorResponse.data) {
          majors.value = majorResponse.data
          
          // 如果有专业信息，设置选中的专业
          if (hierarchy.major) {
            selectedMajor.value = hierarchy.major.orgId
          }
        }
      }
      
      // 设置专业信息
      if (hierarchy.major) {
        orgHierarchy.value.major = hierarchy.major
        
        // 加载该专业下的所有班级
        const classResponse = await request.get(`/organizations/${hierarchy.major.orgId}/children`)
        if (classResponse.data) {
          classes.value = classResponse.data
          
          // 如果有班级信息，设置选中的班级
          if (hierarchy.class) {
            selectedClass.value = hierarchy.class.orgId
          }
        }
      }
      
      // 设置班级信息
      if (hierarchy.class) {
        orgHierarchy.value.class = hierarchy.class
      }
    }
  } catch (error) {
    console.error('加载组织层级信息失败:', error)
    ElMessage.error('加载组织信息失败')
  }
}

// 监听系部选择变化，加载对应专业
watch(selectedDepartment, async (newDeptId) => {
  if (newDeptId) {
    try {
      // 清空专业和班级的选择
      selectedMajor.value = null
      selectedClass.value = null
      classes.value = []
      
      // 加载该院系下的所有专业
      const response = await request.get(`/organizations/${newDeptId}/children`)
      if (response.data) {
        majors.value = response.data
      } else {
        majors.value = []
      }
    } catch (error) {
      console.error('加载专业列表失败:', error)
      ElMessage.error('加载专业列表失败')
      majors.value = []
    }
  } else {
    majors.value = []
    classes.value = []
  }
})

// 监听专业选择变化，加载对应班级
watch(selectedMajor, async (newMajorId) => {
  if (newMajorId) {
    try {
      // 清空班级的选择
      selectedClass.value = null
      
      // 加载该专业下的所有班级
      const response = await request.get(`/organizations/${newMajorId}/children`)
      if (response.data) {
        classes.value = response.data
      } else {
        classes.value = []
      }
    } catch (error) {
      console.error('加载班级列表失败:', error)
      ElMessage.error('加载班级列表失败')
      classes.value = []
    }
  } else {
    classes.value = []
  }
})

const startEdit = () => {
  isEditing.value = true
}

const cancelEdit = () => {
  isEditing.value = false
  loadProfile()
}

const saveProfile = async () => {
  try {
    // 创建提交对象，包含允许编辑的字段
    const updateData = {
      userId: profileData.value.userId,
      fullName: profileData.value.fullName,
      email: profileData.value.email,
      orgId: selectedClass.value // 更新为选择的班级ID
    }
    
    await userStore.updateProfile(updateData)
    isEditing.value = false
    ElMessage.success('个人信息更新成功')
    
    // 重新加载用户信息
    await userStore.getUserInfo()
    loadProfile()
  } catch (error) {
    ElMessage.error('个人信息更新失败')
  }
}

onMounted(() => {
  loadProfile()
})
</script>

<style scoped>
.profile-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 